﻿namespace Hidistro.UI.Web
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Web;
    using System.Web.Configuration;
    using System.Web.Security;
    using wnxd.javascript;

    public class Global : HttpApplication
    {
        private static string isdebug;
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //this.Response.AddHeader("Cache-Control", "public");
            try
            {
                if (Request.UserHostAddress != "::1")
                {
                    string ippath = this.Server.MapPath("~/config/ipconfig.json");
                    if (File.Exists(ippath))
                    {
                        string JumpUrl = File.ReadAllText(ippath);
                        List<IpScope> iplist = GetIP();
                        long ip1 = IP2Long(Request.UserHostAddress), ip2 = 0;
                        string ip = "";
                        if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
                        {
                            ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
                        }
                        else
                        {
                            ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
                        }
                        if (ip != "") ip2 = IP2Long(ip);
                        for (int i = 0; i < iplist.Count; i++)
                        {
                            long min = IP2Long(iplist[i].Min), max = IP2Long(iplist[i].Max);
                            if ((min <= ip1 && ip1 <= max) || (ip != "" && min <= ip2 && ip2 <= max))
                            {
                                this.Server.Transfer(JumpUrl, true);
                                break;
                            }
                        }
                    }
                }
                if (WebConfigurationManager.AppSettings["AccessRecords"] == "true")
                {
                    string path = WebConfigurationManager.AppSettings["ARLogPath"];
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                    sb.AppendLine("连接IP:" + Request.UserHostAddress);
                    string ip = "";
                    if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
                    {
                        ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
                    }
                    else
                    {
                        ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
                    }
                    sb.AppendLine("IP:" + ip);
                    sb.AppendLine("连接主机名:" + Request.UserHostName);
                    sb.AppendLine("页面：" + Request.Url.ToString());
                    sb.AppendLine("浏览器:" + Request.Browser.Browser);
                    sb.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
                    sb.AppendLine("操作系统:" + Request.Browser.Platform);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string FileName;
                    string[] flist = Directory.GetFiles(path, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                    if (flist != null && flist.Length > 0)
                    {
                        FileName = path + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                        FileInfo fileInfo = new FileInfo(FileName);
                        if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                        {
                            FileName = path + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                        }
                    }
                    else
                    {
                        FileName = path + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                    }
                    File.AppendAllText(FileName, sb.ToString(), Encoding.UTF8);
                }

                string str = "AUTHID";
                string formsCookieName = FormsAuthentication.FormsCookieName;
                if (HttpContext.Current.Request.Form[str] != null)
                {
                    this.UpdateCookie(formsCookieName, HttpContext.Current.Request.Form[str]);
                }
                else if (HttpContext.Current.Request.QueryString[str] != null)
                {
                    this.UpdateCookie(formsCookieName, HttpContext.Current.Request.QueryString[str]);
                }
            }
            catch
            {
                
            }
        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            if (isdebug == "false")
            {
                Exception ex = Server.GetLastError().GetBaseException();
                StringBuilder str = new StringBuilder();
                str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                str.AppendLine("客户信息：");
                string ip = "";
                if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
                {
                    ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
                }
                else
                {
                    ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
                }
                str.AppendLine("连接IP:" + Request.UserHostAddress);
                str.AppendLine("IP:" + ip);
                str.AppendLine("连接主机名:" + Request.UserHostName);
                str.AppendLine("浏览器:" + Request.Browser.Browser);
                str.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
                str.AppendLine("操作系统:" + Request.Browser.Platform);
                str.AppendLine("错误信息:");
                str.AppendLine("页面：" + Request.Url.ToString());
                str.AppendLine("错误信息：" + ex.Message);
                str.AppendLine("错误源：" + ex.Source);
                str.AppendLine("异常方法：" + ex.TargetSite);
                str.AppendLine("堆栈信息：" + ex.StackTrace);
                str.AppendLine("--------------------------------------------------------------------------------------------------");
                string upLoadPath = WebConfigurationManager.AppSettings["LogPath"];
                if (!Directory.Exists(upLoadPath))
                {
                    Directory.CreateDirectory(upLoadPath);
                }
                string FileName;
                string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                if (flist != null && flist.Length > 0)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                    FileInfo fileInfo = new FileInfo(FileName);
                    if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                    {
                        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                    }
                }
                else
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                }
                File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
                Server.ClearError();
                HttpContext.Current.Response.Redirect("~/errorinfo.htm");
            }

        }

        protected void Application_Start(object sender, EventArgs e)
        {
            isdebug = System.Configuration.ConfigurationManager.AppSettings["isdebug"].ToString();
        }

        protected void Session_End(object sender, EventArgs e)
        {
        }

        protected void Session_Start(object sender, EventArgs e)
        {
        }

        private void UpdateCookie(string cookie_name, string cookie_value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
            if (cookie == null)
            {
                HttpCookie cookie2 = new HttpCookie(cookie_name, cookie_value);
                base.Response.Cookies.Add(cookie2);
            }
            else
            {
                cookie.Value = cookie_value;
                HttpContext.Current.Request.Cookies.Set(cookie);
            }
        }
        private List<IpScope> GetIP()
        {
            string[] list = File.ReadAllLines(this.Server.MapPath("~/config/ip.json"));
            List<IpScope> islist = new List<IpScope>();
            for (int i = 0; i < list.Length; i++)
            {
                string[] t = list[i].Split('-');
                islist.Add(new IpScope() { Min = t[0], Max = t[1] });
            }
            return islist;
        }
        private static long IP2Long(string ip)
        {
            string[] ipBytes;
            double num = 0;
            if (!string.IsNullOrEmpty(ip))
            {
                ipBytes = ip.Split('.');
                for (int i = ipBytes.Length - 1; i >= 0; i--)
                {
                    num += ((int.Parse(ipBytes[i]) % 256) * Math.Pow(256, (3 - i)));
                }
            }
            return (long)num;
        }
    }
    class IpScope
    {
        public string Min { get; set; }
        public string Max { get; set; }
    }
}

